package net.jueb.frameWorkDemo.mvc4mod.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.web.context.ContextLoader;

import net.jueb.frameWorkDemo.mvc4mod.bean.Account;
import net.jueb.frameWorkDemo.mvc4mod.mapper.AccountMapper;
import net.jueb.frameWorkDemo.mvc4mod.service.IAccountService;

@Component
public class AccountServiceImpl_tx_Default implements IAccountService {

	@Autowired
	private DataSourceTransactionManager txManager;
	
	@Autowired
	private AccountMapper mapper;
	
	@Override
	public Account registAccount(String name,String pwd) {
		Account result=null;
		/**
		 * 自动注入
		 */
		AccountMapper mapper=this.mapper;
		DataSourceTransactionManager txManager=this.txManager;
		DefaultTransactionDefinition def = new DefaultTransactionDefinition();
		def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);// 事物隔离级别，开启新事务
		TransactionStatus status = txManager.getTransaction(def); // 获得事务状态
		try {
			// 逻辑代码，可以写上你的逻辑处理代码
			Account a=new Account();
			a.setNickName(name);
			a.setPasswd(pwd);
			mapper.insert(a);
			txManager.commit(status);
		} catch (Exception e) {
			txManager.rollback(status);
		}
		return result;
	}
	
	public Account registAccount2(String name,String pwd) {
		Account result=null;
		/**
		 * 手动获取获取当前spring上下文
		 */
		AccountMapper mapper=this.mapper;
		DataSourceTransactionManager txManager=ContextLoader.getCurrentWebApplicationContext().getBean("transactionManager",DataSourceTransactionManager.class);
		DefaultTransactionDefinition def = new DefaultTransactionDefinition();
		def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);// 事物隔离级别，开启新事务
		TransactionStatus status = txManager.getTransaction(def); // 获得事务状态
		try {
			// 逻辑代码，可以写上你的逻辑处理代码
			Account a=new Account();
			a.setNickName(name);
			a.setPasswd(pwd);
			mapper.insert(a);
			txManager.commit(status);
		} catch (Exception e) {
			txManager.rollback(status);
		}
		return result;
	}
}
